<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">


    <title>校园订餐系统管理员界面</title>

    <link rel="shortcut icon" href="favicon.ico">
    <link href="css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
    <link href="css/font-awesome.css?v=4.4.0" rel="stylesheet">

    <!-- jqgrid-->
    <link href="css/plugins/jqgrid/ui.jqgrid.css?0820" rel="stylesheet">

    <link href="css/animate.css" rel="stylesheet">
    <link href="css/style.css?v=4.1.0" rel="stylesheet">

    <style>
        /* Additional style to fix warning dialog position */
        #alertmod_table_list_2 {
            top: 900px !important;
        }

    </style>
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content  animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox ">
                <div class="ibox-title">
                    <h5>校园订餐系统窗口列表</h5>
                </div>
                <div class="ibox-content">
                    <div class="jqGrid_wrapper">
                        <table id="table_list_2">
                            <thead>
                            <tr>
                                <th>窗口账号</th>
                                <th>窗口密码</th>
                                <th>窗口名称</th>
                                <th>联系方式</th>
                            </tr>
                            </thead>
                            <tbody id="alertmod_table_list_2">
                            <!-- 使用Thymeleaf迭代数据 -->
                            <tr th:each="window : ${data}">
                                <td th:text="${window.window_id}"></td>
                                <td th:text="${window.window_password}"></td>
                                <td th:text="${window.window_name}"></td>
                                <td th:text="${window.contact}"></td>
                            </tr>
                            </tbody>
                        </table>
                        <div id="pager_list_2"></div>
                    </div>
                    <!-- 添加此div以显示警告消息 -->
                    <div id="alertMessage" class="alert" style="display:none;"></div>
                    <button class="btn btn-primary" data-toggle="modal" data-target="#addWindowModal">新增窗口</button>
                    <button class="btn btn-success" onclick="refreshData()">刷新</button>
                    <button class="btn btn-warning" onclick="editSelectedWindow()">编辑窗口</button>
                    <button class="btn btn-danger" onclick="deleteSelectedWindow()">删除窗口</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="addWindowModal" tabindex="-1" role="dialog" aria-labelledby="addWindowModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addWindowModalLabel">新增窗口</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <!-- 窗口信息表单 -->
                    <form id="addWindowForm">
                        <div class="form-group">
                            <label for="windowId">窗口账号</label>
                            <input type="text" class="form-control" id="windowId" name="window_id" required>
                        </div>
                        <div class="form-group">
                            <label for="windowPassword">窗口密码</label>
                            <input type="password" class="form-control" id="windowPassword" name="window_password" required>
                        </div>
                        <div class="form-group">
                            <label for="windowName">窗口名称</label>
                            <input type="text" class="form-control" id="windowName" name="window_name" required>
                        </div>
                        <div class="form-group">
                            <label for="contact">联系方式</label>
                            <input type="text" class="form-control" id="contact" name="contact" required>
                        </div>
                        <button type="button" class="btn btn-primary" onclick="addWindow()">提交</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="editWindowModal" tabindex="-1" role="dialog" aria-labelledby="editWindowModalLabel" aria-hidden="true">
        <!-- 模态框内容 -->
    </div>

</div>

<!-- 全局js -->
<script src="js/jquery.min.js?v=2.1.4"></script>
<script src="js/bootstrap.min.js?v=3.3.6"></script>
<!-- Peity -->
<script src="js/plugins/peity/jquery.peity.min.js"></script>
<!-- jqGrid -->
<script src="js/plugins/jqgrid/i18n/grid.locale-cn.js?0820"></script>
<script src="js/plugins/jqgrid/jquery.jqGrid.min.js?0820"></script>
<!-- 自定义js -->
<script src="js/content.js?v=1.0.0"></script>
<!-- Page-Level Scripts -->
<script>
    // 全局函数，用于显示警告信息
    function showAlert(message, alertType) {
        // 显示带有淡入淡出效果的警告
        $('#alertMessage').removeClass().addClass('alert ' + alertType).html(message).fadeIn().delay(3000).fadeOut();
    }

    // 全局函数，用于显示成功信息
    function showSuccessAlert(message) {
        showAlert(message, 'alert-success');
    }

    // 全局函数，用于显示错误信息
    function showErrorAlert(message) {
        showAlert(message, 'alert-danger');
    }

</script>
<script>
    $(document).ready(function () {
        $.jgrid.defaults.styleUI = 'Bootstrap';
        // 初始化jqGrid的函数
        function initJqGrid(data) {
            $("#table_list_2").jqGrid({
                datatype: "local",
                data: data,
                height: 450,
                autowidth: true,
                shrinkToFit: true,
                rowNum: 20,
                rowList: [10, 20, 30],
                colNames: ['窗口账号', '窗口密码', '窗口名称', '联系方式'],
                colModel: [
                    { name: "window_id", index: "window_id", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "window_password", index: "window_password", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "window_name", index: "window_name", editable: true, width: 60, sorttype: "string", search: true },
                    { name: "contact", index: "contact", editable: true, width: 60, sorttype: "string", search: true },

                ],
                pager: "#pager_list_2",
                viewrecords: true,
                caption: "窗口详细信息",
                add: true,
                edit: true,
                addtext: 'Add',
                edittext: 'Edit',
                hidegrid: false
            });
            // Add selection
            $("#table_list_2").setSelection(4, true);
            // Setup buttons
            $("#table_list_2").jqGrid('navGrid', '#pager_list_2', {
                edit: true,
                add: true,
                del: true,
                search: true
            }, {
                height: 200,
                reloadAfterSubmit: true
            });
        }

        // 使用AJAX请求从后端获取数据
        $.ajax({
            url: '/backend-api-endpoint/getAllWindows',
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                // 初始化jqGrid
                initJqGrid(data);
            },
            error: function (error) {
                console.error('Error fetching data from the server:', error);
            }
        });
    });

    // 刷新数据函数
    function refreshData() {
        // 使用AJAX请求从后端获取数据
        $.ajax({
            url: '/backend-api-endpoint/getAllWindows',
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                // 清空表格数据
                $("#table_list_2").jqGrid('clearGridData');
                // 添加新数据
                for (var i = 0; i < data.length; i++) {
                    $("#table_list_2").jqGrid('addRowData', i + 1, data[i]);
                }

                console.log('Data refreshed successfully.');
            },
            error: function (error) {
                console.error('Error fetching data from the server:', error);
            }
        });
    }

    // 新增窗口函数
    function addWindow() {
        // 获取表单数据
        var userData = {
            window_id: $("#windowId").val(),
            window_password: $("#windowPassword").val(),
            window_name: $("#windowName").val(),
            contact: $("#contact").val(),
        };
        // 发送数据到后端
        $.ajax({
            url: '/backend-api-endpoint/addWindow',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(userData),
            success: function (response) {
                console.log(response);
                refreshData();
                showSuccessAlert('窗口添加成功！');
            },
            error: function (error) {
                console.error('添加窗口时出错：', error);
                showErrorAlert('添加窗口时出错，请重试。');
            }
        });
        // 关闭模态框
        $('#addWindowModal').modal('hide');


    }

    function editSelectedWindow() {
        // 获取所选行的ID
        var selectedRowId = $("#table_list_2").jqGrid('getGridParam', 'selrow');

        if (!selectedRowId) {
            alert('请先选择要编辑的窗口。');
            return;
        }
        // 获取所选行的数据
        var selectedUserData = $("#table_list_2").jqGrid('getRowData', selectedRowId);

        // 打开编辑模态框
        openEditWindowModal(selectedUserData);
    }

    function openEditWindowModal(userData) {
        // 填充模态框内容
        var modalContent = '<div class="modal-dialog" role="document">';
        modalContent += '<div class="modal-content">';
        modalContent += '<div class="modal-header">';
        modalContent += '<h5 class="modal-title" id="editWindowModalLabel">编辑窗口</h5>';
        modalContent += '<button type="button" class="close" data-dismiss="modal" aria-label="Close">';
        modalContent += '<span aria-hidden="true">&times;</span>';
        modalContent += '</button>';
        modalContent += '</div>';
        modalContent += '<div class="modal-body">';
        modalContent += '<!-- 窗口信息表单 -->';
        modalContent += '<form id="editWindowForm">';
        modalContent += '<div class="form-group">';
        modalContent += '<label for="editWindowId">窗口账号</label>';
        modalContent += '<input type="text" class="form-control" id="editWindowId" name="window_id" value="' + userData.window_id + '" required>';
        modalContent += '</div>';
        modalContent += '<div class="form-group">';
        modalContent += '<label for="editWindowPassword">窗口密码</label>';
        modalContent += '<input type="password" class="form-control" id="editWindowPassword" name="window_password" value="' + userData.window_password + '" required>';
        modalContent += '</div>';
        modalContent += '<div class="form-group">';
        modalContent += '<label for="editWindowName">窗口名称</label>';
        modalContent += '<input type="text" class="form-control" id="editWindowName" name="window_name" value="' + userData.window_name + '" required>';
        modalContent += '</div>';
        modalContent += '<div class="form-group">';
        modalContent += '<label for="editContact">联系方式</label>';
        modalContent += '<input type="text" class="form-control" id="editContact" name="contact" value="' + userData.contact + '" required>';
        modalContent += '</div>';
        modalContent += '<button type="button" class="btn btn-primary" onclick="saveEditedWindow()">保存</button>';
        modalContent += '</form>';
        modalContent += '</div>';
        modalContent += '</div>';
        modalContent += '</div>';
        modalContent += '</div>';

        // 将模态框内容添加到模态框中
        $("#editWindowModal").html(modalContent);

        // 打开模态框
        $('#editWindowModal').modal('show');
    }

    // 保存编辑后的窗口函数
    function saveEditedWindow() {
        console.log('点击保存按钮。'); // 为了调试添加这一行

        // 获取表单数据
        var editedUserData = {
            window_id: $("#editWindowId").val(),
            window_password: $("#editWindowPassword").val(),
            window_name: $("#editWindowName").val(),
            contact: $("#editContact").val(),
        };

        // 发送数据到后端
        $.ajax({
            url: '/backend-api-endpoint/editWindow',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(editedUserData),
            success: function (response) {
                // 处理成功响应，可以根据需要刷新窗口列表等操作
                console.log(response);
                // 关闭模态框
                $('#editWindowModal').modal('hide');
                // 刷新数据
                refreshData();
                showSuccessAlert('编辑成功！');

            },
            error: function (error) {
                showSuccessAlert('编辑失败！');

                console.error('Error editing user:', error);
                // 输出服务器返回的错误消息
                console.error('Server error message:', error.responseText);
            }
        });


    }
    function deleteSelectedWindow() {
        // 获取所选行的ID
        var selectedRowId = $("#table_list_2").jqGrid('getGridParam', 'selrow');

        if (!selectedRowId) {
            alert('请先选择要删除的窗口。');
            return;
        }

        // 获取所选行的数据
        var selectedUserData = $("#table_list_2").jqGrid('getRowData', selectedRowId);

        // 弹出确认框
        var confirmation = confirm('您确定要删除窗口吗？');

        if (confirmation) {
            // 发送数据到后端进行删除
            $.ajax({
                url: '/backend-api-endpoint/deleteWindow',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({window_id: selectedUserData.window_id}),
                success: function (response) {
                    // 处理成功响应，可以根据需要刷新窗口列表等操作
                    console.log(response);
                    // 刷新数据
                    refreshData();
                    showSuccessAlert('删除成功！');
                },
                error: function (error) {
                    showSuccessAlert('删除失败！');
                    console.error('Error deleting user:', error);
                    // 输出服务器返回的错误消息
                    console.error('Server error message:', error.responseText);
                }
            });
        }
    }

</script>

</body>

</html>
